package Classes
{
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class Skill extends EventDispatcher
	{
		private var m_target:Entity;
		private var m_name:String;
		private var m_owner:Entity;
		private var m_config:Object;
		private var m_lastCastTime:int; 
		private var m_castTime:int;
		
		public var range:Number;
		public var cooldown:int = 1500;
		
		private var m_castTimer:Timer = new Timer(0);
		
		public function Skill(name:String, owner:Entity,target:Entity=null)
		{
			m_name = name;
			m_owner = owner;
			m_target = target;
		}
		
		public function isCasting():Boolean{
			return (m_castTimer.running);
		}
		
		public function isInRange():Boolean{
			var ownerTargetDistance:Number = m_owner.getRigidBodyComponent().getPosition().subtract(m_target.getRigidBodyComponent().getPosition()).length;
			return (ownerTargetDistance <= range);
		}
		
		public function clone():Skill{
			var skill:Skill = new Skill(m_name, m_owner, m_target);
			skill.config = m_config;
			return skill;
		}
		
		public function set castTime(time:int):void{
			m_castTime = time;
		}
		
		public function get castTime():int{
			return m_castTime;
		}
		
		public function get name():String{
			return m_name;
		}
		
		public function set config(config:Object):void{
			m_config = config;
		}
		
		public function get config():Object{
			return m_config;
		}
		
		public function set target(target:Entity):void{
			m_target = target;
		}
		
		public function get target():Entity{
			return m_target;
		}
		
		public function set owner(owner:Entity):void{
			m_owner = owner;
		}
		
		public function get owner():Entity{
			return m_owner;
		}
		
		public function process():void{
			var owner:Entity = m_owner;
			var target:Entity = m_target;
			
			cast();
		}
		
		public function cast():void{
			m_castTimer.delay = m_castTime;
			m_castTimer.addEventListener(TimerEvent.TIMER, onCastComplete);
			m_castTimer.start();
		}

		private function onCastComplete(te:TimerEvent):void{
			m_castTimer.stop();
			m_castTimer.reset();
			m_castTimer.removeEventListener(TimerEvent.TIMER, onCastComplete);
			var skillEntity:Entity = owner.getRigidBodyComponent().getWorld().entityManager.createSkill(this);
			skillEntity.getAIComponent().engage(target);
			skillEntity.addEventListener(GameEvent.DESTINATION_REACHED, onSkillContact);			
		}
		
		private function onSkillContact(ge:GameEvent):void{
			var skillEntity:Entity = ge.currentTarget as Entity;
			skillEntity.removeEventListener(GameEvent.DESTINATION_REACHED, onSkillContact);
			skillEntity.destroy();
		}

	}
}